package com.ace.token.common.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * redis扩展功能
 * @Author
 * @Date 2018年07月04日 下午5:09
 */
@Component
public class RedisOperation {


    @Autowired
    private RedisTemplate<String, Object> template;

    /**
     * 设置存活时间
     * @param key
     * @param time
     * @param unit
     */
    public void expire(String key, Long time, TimeUnit unit){
        template.expire(key,time,unit);
    }


    /**
     * 设置存活时间,默认为秒
     * @param key
     * @param time
     */
    public void expire(String key, Long time){
        expire(key,time,TimeUnit.SECONDS);
    }


    /**
     * 模糊查询key
     * @return
     */
    public Set<String> selectKeys(String keys){
        Set<String> results = template.keys(keys);
        return results;
    }

    /**
     * 删除key 支持模糊删除 *:key:*
     * @param key
     */
    public void delete(String key){
        Set<String> keys = template.keys(key);
        template.delete(keys);
    }

    /**
     * 批量删除,不支持模糊删除
     * 自动过滤null
     * @param keys
     */
    public void delete(String ... keys){
      List<String> keyList = Arrays.asList(keys)
                                     .stream()
                                     .filter(key -> key!=null)
                                     .collect(Collectors.toList());
        template.delete(keyList);
    }


}
